package com.aloda.config;

import com.aloda.interceptor.AdminLoginInterceptor;
import com.aloda.interceptor.RecordInterceptor;
import com.aloda.interceptor.UserLoginInterceptor;
import com.aloda.interceptor.UserRefreshTokenInterceptor;
import com.aloda.properties.FileUploadProperties;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Slf4j
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Resource
    private AdminLoginInterceptor adminLoginInterceptor;

    @Resource
    private UserRefreshTokenInterceptor userRefreshTokenInterceptor;

    @Resource
    private UserLoginInterceptor userLoginInterceptor;

    @Resource
    private FileUploadProperties fileUploadProperties;

    @Resource
    private RecordInterceptor recordInterceptor;

    /**
     * 处理跨域请求
     * @return
     */
    @Bean
    public FilterRegistrationBean<CorsFilter> corsFilter() {
        log.info("开启跨域请求配置...");
        FilterRegistrationBean<CorsFilter> registrationBean = new FilterRegistrationBean<>();
        registrationBean.setFilter(new CorsFilter());
        registrationBean.addUrlPatterns("/*"); // 应用到所有URL
        return registrationBean;
    }


    /**
     * 自定义拦截器配置
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        log.info("开始注册自定义拦截器...");
        registry.addInterceptor(adminLoginInterceptor)
                .addPathPatterns("/admin/**")
                .excludePathPatterns("/admin/emp/login");
        registry.addInterceptor(recordInterceptor)
                .addPathPatterns("/user/**")
                .order(0);
        registry.addInterceptor(userRefreshTokenInterceptor)
                .addPathPatterns("/user/**")
                .excludePathPatterns("/user/user/login")
                .excludePathPatterns("/user/user/register")
                .excludePathPatterns("/user/page/about")
                .order(1);
        registry.addInterceptor(userLoginInterceptor)
                .addPathPatterns("/user/**")
                .excludePathPatterns("/user/user/login")
                .excludePathPatterns("/user/user/register")
                .excludePathPatterns("/user/page/about")
                .order(2);
    }

    /**
     * 静态资源映射
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        log.info("开始设置静态资源映射...");
        registry.addResourceHandler("upload/**")
                .addResourceLocations("file:" +fileUploadProperties.getUploadPath()+"/");
    }
}
